#pragma once

#include <memory>
#include <unordered_map>
#include <functional>
#include <thread>
#include <vector>
#include <atomic>
#include <mutex>
#include <future>
#include <chrono>
#include "Tcp_Server.hpp"
#include "Ctrl.hpp"
#include "Kv_cluster.hpp"

// 先声明命名空间
namespace Reactor_Module {

using namespace std;
using namespace Business_Ctrl;
using namespace Redis_Cluster_Model;
using namespace Log_Module;

class ReactorServer {
private:
    unique_ptr<Tcp_Server> _tcp_server;
    shared_ptr<MultiLevelController> _biz_controller;
    atomic<bool> _is_running{false};
    thread _server_thread;
    mutable mutex _server_mutex;
    
    // 事件处理器
    string requestHandler(string& request) {
        // 检查空请求
        if (request.empty()) {
            LOG(LogLevel::WARNING) << "Received empty request";
            return BizResult(false, "", "空请求", 400).serialize();
        }
        
        // 移除可能的空白字符
        size_t start = request.find_first_not_of(" \t\n\r");
        size_t end = request.find_last_not_of(" \t\n\r");
        
        if (start == string::npos) { // 全是空白字符
            LOG(LogLevel::WARNING) << "Received request with only whitespace";
            return BizResult(false, "", "无效请求", 400).serialize();
        }
        
        request = request.substr(start, end - start + 1);
        LOG(LogLevel::INFO) << "Processing request: '" << request << "'";
        
        try {
            // 使用锁保护业务控制器访问
            lock_guard<mutex> lock(_server_mutex);
            if (!_biz_controller) {
                LOG(LogLevel::ERROR) << "Business controller is null";
                return BizResult(false, "", "控制器不可用", 500).serialize();
            }
            
            BizResult result = _biz_controller->执行命令(request);
            string response = result.serialize();
            
            LOG(LogLevel::INFO) << "Request processed, result: " << (result.成功 ? "SUCCESS" : "FAILED");
            return response;
        } catch (const exception& e) {
            LOG(LogLevel::ERROR) << "Request processing error: " << e.what();
            return BizResult(false, "", string("内部服务器错误: ") + e.what(), 500).serialize();
        }
    }
    
    // 服务器运行函数
    void runServer() {
        try {
            LOG(LogLevel::INFO) << "Reactor server starting";
            _tcp_server->InitServer();
            _is_running = true;
            
            // 主服务器循环
            _tcp_server->Start();
            
        } catch (const exception& e) {
            LOG(LogLevel::ERROR) << "Server run error: " << e.what();
            _is_running = false;
        }
    }

public:
    ReactorServer(int port = 8082, 
                 shared_ptr<MultiLevelController> controller = nullptr)
        : _biz_controller(controller) {
        
        if (!_biz_controller) {
            // 创建默认的业务控制器
            _biz_controller = make_shared<MultiLevelController>();
        }
        
        // 创建TCP服务器，绑定业务处理器
        _tcp_server = make_unique<Tcp_Server>(
            [this](string& request) { return this->requestHandler(request); },
            port
        );
        
        LOG(LogLevel::INFO) << "ReactorServer created on port " << port;
    }

    // 启动Reactor服务器
    bool start() {
        if (_is_running) {
            LOG(LogLevel::WARNING) << "Reactor server is already running";
            return false;
        }

        try {
            // 在新线程中启动服务器
            _server_thread = thread(&ReactorServer::runServer, this);
            
            // 等待服务器启动
            for (int i = 0; i < 10; i++) { // 最多等待1秒
                if (_is_running) break;
                this_thread::sleep_for(chrono::milliseconds(100));
            }
            
            if (_is_running) {
                LOG(LogLevel::INFO) << "Reactor server started successfully";
                return true;
            } else {
                LOG(LogLevel::ERROR) << "Reactor server failed to start";
                return false;
            }
        } catch (const exception& e) {
            LOG(LogLevel::ERROR) << "Failed to start reactor server: " << e.what();
            return false;
        }
    }

    // 停止服务器
    void stop() {
        if (_is_running) {
            LOG(LogLevel::INFO) << "Stopping reactor server...";
            _is_running = false;
            
            // 停止TCP服务器
            if (_tcp_server) {
                _tcp_server->Stop();
            }
            
            // 等待服务器线程结束
            if (_server_thread.joinable()) {
                _server_thread.join();
                LOG(LogLevel::INFO) << "Server thread stopped";
            }
            
            LOG(LogLevel::INFO) << "Reactor server stopped";
        }
    }

    // 设置业务控制器
    void setController(shared_ptr<MultiLevelController> controller) {
        lock_guard<mutex> lock(_server_mutex);
        _biz_controller = controller;
    }

    // 获取业务控制器
    shared_ptr<MultiLevelController> getController() const {
        lock_guard<mutex> lock(_server_mutex);
        return _biz_controller;
    }

    // 检查服务器是否运行
    bool isRunning() const {
        return _is_running.load();
    }

    ~ReactorServer() {
        LOG(LogLevel::INFO) << "ReactorServer destructor called";
    }
};

// 集群Reactor服务器（支持分布式部署）
class ClusterReactorServer {
private:
    vector<unique_ptr<ReactorServer>> _servers;
    shared_ptr<KvCluster> _cluster;
    atomic<bool> _is_running{false};
    vector<thread> _cluster_threads;
    mutable mutex _cluster_mutex;
    
public:
    ClusterReactorServer(shared_ptr<KvCluster> cluster)
        : _cluster(cluster) {
        LOG(LogLevel::INFO) << "ClusterReactorServer created";
    }
    
    // 启动多个Reactor实例
    bool startCluster(const vector<int>& ports) {
        if (_is_running) {
            LOG(LogLevel::WARNING) << "Cluster reactor is already running";
            return false;
        }
        
        try {
            // 启动集群管理
            if (_cluster) {
                _cluster->start();
            }
            
            // 清空之前的线程
            {
                lock_guard<mutex> lock(_cluster_mutex);
                _cluster_threads.clear();
                _servers.clear();
            }
            
            // 启动多个服务器实例
            for (int port : ports) {
                auto controller = make_shared<MultiLevelController>(nullptr, _cluster);
                auto server = make_unique<ReactorServer>(port, controller);
                
                // 在新线程中启动每个服务器
                _cluster_threads.emplace_back([server = move(server)]() {
                    if (server->start()) {
                        LOG(LogLevel::INFO) << "Cluster node started successfully";
                        // 保持线程运行
                        while (server->isRunning()) {
                            this_thread::sleep_for(chrono::seconds(1));
                        }
                    } else {
                        LOG(LogLevel::ERROR) << "Cluster node failed to start";
                    }
                });
                
                {
                    lock_guard<mutex> lock(_cluster_mutex);
                    _servers.push_back(move(server));
                }
            }
            
            _is_running = true;
            LOG(LogLevel::INFO) << "Cluster reactor started with " << ports.size() << " nodes";
            return true;
            
        } catch (const exception& e) {
            LOG(LogLevel::ERROR) << "Failed to start cluster reactor: " << e.what();
            return false;
        }
    }
    
    void stopCluster() {
        if (_is_running) {
            LOG(LogLevel::INFO) << "Stopping cluster reactor...";
            _is_running = false;
            
            // 停止所有服务器
            {
                lock_guard<mutex> lock(_cluster_mutex);
                for (auto& server : _servers) {
                    if (server) {
                        server->stop();
                    }
                }
            }
            
            // 等待所有线程结束
            for (auto& thread : _cluster_threads) {
                if (thread.joinable()) {
                    thread.join();
                }
            }
            
            // 清理资源
            {
                lock_guard<mutex> lock(_cluster_mutex);
                _cluster_threads.clear();
                _servers.clear();
            }
            
            if (_cluster) {
                _cluster->stop();
            }
            
            LOG(LogLevel::INFO) << "Cluster reactor stopped";
        }
    }
    
    // 获取集群状态
    bool isRunning() const {
        return _is_running.load();
    }
    
    ~ClusterReactorServer() {
        LOG(LogLevel::INFO) << "ClusterReactorServer destructor called";
    }
};

} 